import { NextFunction, Request, Response } from "express";

import fs from 'fs-extra'

import userService from '../user/service'
import Base from "../../common/controller/base";
import { getUserInfo, resolve } from "../../utils/common";
import { getAvatarUrl, resolveFile } from "./util";
import { BASE_URL } from "../../config/conf";


class UploadController extends Base {
    /**
     * 上传头像
     * @param req 
     * @param res 
     */
    uploadAvatar = async (req: Request, res: Response, next: NextFunction) => {
        resolveFile(req, async (files: any) => {
            const file = files.avatar
            // 检验参数是否正确
            if (!file) return next({ msg: '参数不正确', code: 400 })
            const realFile = file[0];

            // 检验文件格式
            if (!(/\.jpg|\.jpeg|\.png/.test(realFile.originalFilename))) {
                return next({ msg: '不支持该格式的文件或图片', code: 200 })
            }
            // 生成文件名
            const name = Date.now() + '.' + realFile.originalFilename.split('.')[1]
            try {
                // 将头像移动到avatar文件夹中
                fs.move(realFile.path, resolve(`../public/avatar/${name}`), { overwrite: true })


                const url = `http://${BASE_URL}/${name}`;
                // 得到用户的id
                const { id } = getUserInfo(req);

                // 更改数据库中该用户的信息
                // 获取原来的头像,移除该文件
                const oldAvatar = await userService.getOldUrl(id)
                const isSucc = await userService.updateAvatar(url, id)

                // 更改成功
                if (isSucc) {
                    if (oldAvatar.avatar) {
                        // 如果原来有旧头像，删除
                        try {
                            fs.unlink(resolve(`../public/avatar/${getAvatarUrl(oldAvatar.avatar)}`))
                        } catch (e) {
                        }
                    }
                    this.success(res, { msg: '上传头像成功', data: { url } })
                }
            } catch (e) {
                next({ msg: '服务器出错', code: 500 })
            }
        })
    }
}

export default new UploadController;